<template>
  <h3>toRef, toRefs 函数的演示 (打开调试器查看日志消息)</h3>

  <hr>
  <div>个人信息 (<b>toRef</b> 演示):</div>
  <div class="single">姓名: {{name}}</div>
  <div class="single">年龄: {{age}}</div>
  <div class="single">薪水: {{salary}}K</div>
  <div>所有信息: {{person}}</div>

  <button @click="name += '~'">修改姓名</button>
  <button @click="age++">修改年龄</button>
  <button @click="salary++">涨薪</button>

  <hr>
  <div>书籍信息 (<b>toRefs</b> 演示)</div>
  <div class="single">作者: {{author}}</div>
  <div class="single">价格: ${{price}}</div>
  <div class="single">流派: {{category.sect}}</div>
  <div>所有信息: {{book}}</div>

  <button @click="author += '#'">修改作者</button>
  <button @click="price++">修改价格</button>
  <button @click="category.sect += '**'">修改流派</button>

  <hr>
  <div>坐标: (toRef 作用于普通对象的例子) {{posX}}</div>
  <button @click="posX++">posX 加一</button>
  <br>
  <br>
  <div>坐标: (toRefs 作用于普通对象的例子) {{test}}</div>
  <button @click="test.x++">x 加一</button>
  <button @click="test.y++">y 加一</button>
  <br>
  <br>
  <button @click="showAll">显示所有相关对象的值</button>
  <span>{{msg}}</span>
  <hr>
  <p>
    注意:<br>
    1. toRef创建一个引用类型的ref对象, 主要用于将响应式对象中的某个属性单独提供给外部使用.<br>
    2. toRefs可以将对象（只能接收ractive对象）中的属性变成响应式,以方便使用.<br>
    3. toRef直接作用于普通对象时,得到的对象不是响应式的; 而toRefs应该只用于reactive对象,如果直接用于普通对象,则会报错,且得到的对象也不是响应式的.<br>
  </p>
</template>

<script>
import { ref, reactive, toRef, toRefs } from 'vue'

export default {
  setup() {
    let person = reactive({
      name: '张三',
      age: 33,
      job: {
        job1: {
          salary: 22
        }
      },
    })

    let book = reactive({
      author: 'Jack',
      price: 98,
      category: {
        sect: 'futurism'
      }
    })

    //incorrect usage:

    let position = {
      x: 0,
      y: 0
    }

    let posX = toRef(position, 'x')
    console.log('posX=', posX)

    let test = toRefs(position)
    console.log('test=', test)

    let msg = ref('')
    
    function showAll() {
      msg.value = 'position: ' + position.x + 'x' + position.y + ', posX=' + posX.value + ', test=' + test.x.value + '*' + test.y.value
    }

    //expose 
    return {
      person,
      name: toRef(person, 'name'),
      age: toRef(person, 'age'),
      salary: toRef(person.job.job1, 'salary'),

      book,
      ...toRefs(book),

      posX,
      test,
      msg,
      showAll
    }
  },
}
</script>

<style scoped>

h3 {
  text-align: center;
}

.single {
  margin-top: 5px;
}

</style>